package edu.langnan.xiaoli.controller.business;

import edu.langnan.xiaoli.base.AjaxResult;
import edu.langnan.xiaoli.base.controller.BaseController;
import edu.langnan.xiaoli.config.security.TokenService;
import edu.langnan.xiaoli.constant.XiaoLiConstants;
import edu.langnan.xiaoli.core.domain.CarPoolDO;
import edu.langnan.xiaoli.core.dto.CarPoolDTO;
import edu.langnan.xiaoli.exception.CustomException;
import edu.langnan.xiaoli.service.CarPoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author cql
 */
@RestController
@RequestMapping("car")
public class CarPoolController extends BaseController {

    @Autowired
    private CarPoolService carPoolService;

    @Autowired
    private TokenService tokenService;

    /**
     * 新增拼车或修改拼车
     *
     * @return
     */
    @PostMapping
    public AjaxResult saveOrUpdate(@RequestBody CarPoolDO carPoolDO, HttpServletRequest request) {
        /**
         * 设置当前用户信息
         */
        Integer id = tokenService.getLoginUser(request).getId();
        carPoolDO.setStuId(id);
        carPoolService.saveOrUpdate(carPoolDO);
        return AjaxResult.success();
    }

    /**
     * 查找当前登录用户正在进行的拼车,因为系统规定一个用户只能有一条正在进行中的拼车，如果如果有多条，则会抛出异常
     *
     * @return
     */
    @GetMapping
    public AjaxResult findCaring(HttpServletRequest request) {
        Integer stuId = tokenService.getLoginUser(request).getId();
        List<CarPoolDTO> carPoolDTOS = carPoolService.carpoolList("", XiaoLiConstants.PUBLISH_STATUS, stuId);
        // if (carPoolDTOS.size() > XiaoLiConstants.CARING_COUNT) {
        //     return AjaxResult.error();
        // }
        return AjaxResult.success(carPoolDTOS);
    }


    /**
     * 查看登录用户历史拼车
     *
     * @param request
     * @return
     */
    @GetMapping("history")
    public AjaxResult carHistory(HttpServletRequest request) {
        Integer stuId = tokenService.getLoginUser(request).getId();
        List<CarPoolDTO> result = carPoolService.carHistory(stuId);
        return AjaxResult.success(result);
    }

}
